from flask_restful import Resource
from common.models.index import *
from common.utils.data2 import datalist2dict,data2dict
from common.utils.shopping_redis import redis_client
import json

# 商品分类资源类
class Shopping_Category(Resource):
    def get(self):
        # 从Redis读取数据
        data_catch = redis_client.get('index_category')
        if data_catch: # 如果Redis数据库中有数据，则返回Redis中的数据
            return json.loads(data_catch) # 将字符串转换成字典类型
        else: # 如果Redis中没有数据，则从mysql查询数据，返回给用户，并且写入Redis
            data = self.getData(0)
            if data:
                # 以父id来循环遍历剩下的子id
                for item in data:
                    item.update({'list':''})
                    data_second = self.getData(int(item['id']))
                    item['list'] = data_second
                    for item1 in data_second:
                        item1.update({'list':''})
                        data_third = self.getData(int(item1['id']))
                        item1['list'] = data_third
                # 将数据查询得到的数据缓存到Redis中
                redis_client.setex('index_category',3600,json.dumps(data)) # 缓存过期时间3600秒 24小时 字典类型转换成字符串
                return data
            else:
                return {'message':'None'}

    @staticmethod
    def getData(parent_id):
        res = Category.query.with_entities(Category.id, Category.parent_id, Category.name).filter(
            Category.parent_id == parent_id).order_by(Category.sort.asc()).limit(10).all()  # 升序排序
        if res:
            return datalist2dict(res)
        else:
            return 'None'


# 首页新品推荐的资源类
class Shopping_HomeNewProduct(Resource):
    def get(self):
        # 写入缓存
        data_cache = redis_client.get('index_HomeNewProduct')
        if data_cache:
            return json.loads(data_cache)
        else:
            # 联立两张表，查询
            res = HomeNewProduct.query.join(Product,HomeNewProduct.product_id==Product.id).with_entities(
                                            Product.id,Product.default_pic,Product.price,Product.product_name,
                                            Product.rel_category3_id).order_by(
                                            HomeNewProduct.sort.desc()).limit(10).all()
            if res:
                data = datalist2dict(res)
                redis_client.setex('index_HomeNewProduct',3600,json.dumps(data))
                return data
            else:
                return {'message':'None'}

# 首页人气热搜的资源类
class Shopping_HomeRecommendProduct(Resource):
    def get(self):
        # 缓存处理
        data_cache = redis_client.get('index_HomeRecommendProduct')
        if data_cache:
            return json.loads(data_cache)
        else:
            res = HomeRecommendProduct.query.join(Product,
                                                  HomeRecommendProduct.product_id==Product.id
                                                  ).with_entities(Product.id,Product.default_pic,
                                                                  Product.product_name,
                                                                  Product.rel_category3_id,
                                                                  Product.price).limit(10).all()
            if res:
                data = datalist2dict(res)
                # 将查询到的数据存入Redis
                redis_client.setex('index_HomeRecommendProduct',3600,json.dumps(data))
                return data
            else:
                return {'message':'None'}


# 首页专题分类资源
class Shopping_RecommendSubject(Resource):
    def get(self):
        res = CmsSubject.query.filter(
            CmsSubject.show_status == 1).all()

        res_list = []
        for res_obj in res:
            if res_obj:
                data = data2dict(res_obj)
                res_product = CmsSubjectProductRelation.query.join \
                    (Product, CmsSubjectProductRelation.product_id == Product.id).filter \
                    (CmsSubjectProductRelation.subject_id == res_obj.id).with_entities \
                    (Product.id, Product.default_pic, Product.price, Product.product_name,
                     Product.rel_category3_id).limit(10).all()
                if res_product:
                    data_product = datalist2dict(res_product)
                    data['productList'] = data_product
                    res_list.append(data)
        if len(res_list) > 0:
            return res_list
        else:
            return {'message': 'none'}
